package br.com.upper.util;

import javax.transaction.Transaction;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;


public class HibernateUtil {
	
	private static final SessionFactory sessionFactory;

	static {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			AnnotationConfiguration acfg = new AnnotationConfiguration();
			acfg.configure();
			sessionFactory = acfg.buildSessionFactory();
		} catch (Throwable ex) {
			// Log exception
			System.err.println("Falha criacao SessionFactory inicial");
			System.err.println(ex);
			throw new ExceptionInInitializerError(ex);
		}
	}
	
	public static Session beginTransaction() {
		Session session = getSession();
		session.beginTransaction();
		return session;
	}
		 
	public static void commitTransaction() {
		getSession().getTransaction().commit();
	}
		 
	public static void rollbackTransaction() {
		getSession().getTransaction().rollback();
	}
	
	public static org.hibernate.Transaction getTransaction() {
		return getSession().getTransaction();
	}
		 
	public static void closeSession() {
		getSession().close();
	}

	public static Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	
}
